<template>
    <rx-dialog @handOk="onOk" @cancel="cancel">
        <rx-layout>
            <div slot="center">
                <a-form :form="form" layout="vertical" class="rx-a-form-vertical">

                    <a-form-item  :label="i18n('form.valueSource','值来源')">
                        <a-radio-group :options="fromOptions" @change="fromChange" v-decorator="['from',{rules: [{ required: true, message: i18n('form.valueSource','值来源','select') }] }]" />
                    </a-form-item>
                    <div v-show="from=='distinct'">
                        <a-form-item  :label="i18n('form.matchingMode','匹配方式')">
                            <a-radio-group buttonStyle="solid" @change="typeChange" v-decorator="['distinct_type',{rules: [{ required: from=='distinct', message: i18n('form.matchingMode','匹配方式','select') }] }]">
                                <a-radio-button value="select">{{i18n('form.selectField','选择字段')}}</a-radio-button>
                                <a-radio-button value="table">{{i18n('form.databaseTable','数据库表')}}</a-radio-button>
                                <a-radio-button value="dictionary">{{i18n('form.dict','数据字典')}}</a-radio-button>
                            </a-radio-group>
                        </a-form-item>
                        <a-form-item v-show="distinct_type=='select'" :label="i18n('form.displayField','显示字段')">
                            <a-select :options="fieldDatas" allowClear v-decorator="['bindField',{rules: [{ required: false, message: i18n('form.displayField','显示字段','select')}]}]" />
                        </a-form-item>

                        <div v-show="distinct_type=='table'">
                            <a-form-item  :label="i18n('form.dataSource','数据源')">
                                <rx-input-button ref="dsName" v-decorator="['dsName',{rules: [{ required: false, message: i18n('form.dataSource','数据源','select')}]}]" @click="openDataSource" style="width: 70%;"></rx-input-button>
                            </a-form-item>
                            <a-form-item  :label="i18n('form.selTable','选择表')">
                                <rx-input-button ref="tableName" v-decorator="['tableName',{rules: [{ required: distinct_type=='table', message: i18n('form.selTableTips','请选择表')}]}]"  @click="onTableMap" style="width: 70%;"></rx-input-button>
                            </a-form-item>
                            <a-form-item  :label="i18n('form.conditionField','条件字段')">
                                <a-select v-decorator="['searchField',{rules: [{ required: distinct_type=='table', message: i18n('form.conditionField','条件字段','select')}]}]" :options="matchCol" allowClear style="width: 70%;">
                                </a-select>
                            </a-form-item>
                            <a-form-item  :label="i18n('form.displayField','显示字段')">
                                <a-select v-decorator="['displayField',{rules: [{ required: distinct_type=='table', message: i18n('form.displayField','显示字段','select')}]}]" :options="matchCol" allowClear style="width: 70%;">
                                </a-select>
                            </a-form-item>

                        </div>

                        <a-form-item v-show="distinct_type=='dictionary'" :label="i18n('list.dictionary','匹配字典')">
                            <rx-input-button v-decorator="['displayDicKey_name',{rules: [{ required: distinct_type=='dictionary', message: i18n('list.dictionary','匹配字典','select')}]}]"
                                             @click="selectDic($event,'displayDicKey')"
                                             style="width: 100%;">
                            </rx-input-button>
                            <a-input v-decorator="['displayDicKey']" style="display: none;"/>
                        </a-form-item>

                    </div>

                    <a-form-item v-show="from=='self'" :label="i18n('list.option','选项')">
                        <div class="table-operator">
                            <a-button @click="addRow">{{$ti18('rxList.add','新增')}}</a-button>
                            <a-button @click="removeRow">{{$ti18('rxList.delBtn','删除')}}</a-button>
                            <a-button @click="upRow">{{i18n('list.upward','向上')}}</a-button>
                            <a-button @click="downRow">{{i18n('list.down','向下')}}</a-button>
                        </div>
                        <rx-grid ref="props"
                                 :bordered="true"
                                 :allowRowSelect="true"
                                 :multiSelect="true"
                                 style="min-height:300px;"
                                 :dataSource="dataSource"
                                 :columns="columns"
                                 :showPage="false">
                                      <span slot="name" slot-scope="{text,record,index,blur}">
                                        <a-input v-model="record.name" @blur="blur(index,'name',text,record)" />
                                      </span>
                            <span slot="key" slot-scope="{text,record,index,blur}">
                                        <a-input v-model="record.key" @blur="blur(index,'key',text,record)" />
                                      </span>
                        </rx-grid>
                    </a-form-item>

                    <div v-show="from=='url'">
                        <a-form-item  label="JSON URL">
                            <a-input v-decorator="['url',{rules: [{ required: from=='url',message: i18nRequired('form.url','URL必填')}] }]"/>
                        </a-form-item>

                        <a-form-item  :label="i18n('form.textField','文本字段')">
                            <a-input v-decorator="['url_textfield',{rules: [{ required: from=='url',message: i18nRequired('form.textField','文本字段必填')}] }]"/>
                        </a-form-item>

                        <a-form-item  :label="i18n('form.numberField','数值字段')">
                            <a-input v-decorator="['url_valuefield',{rules: [{ required: from=='url',message: i18nRequired('form.numberField','数值字段必填')}] }]"/>
                        </a-form-item>

                    </div>

                    <a-form-item v-show="from=='dic'" :label="i18n('form.dataDicItem','数据字典项')">
                        <rx-input-button v-decorator="['dicKey_name',{rules: [{ required: from=='dic', message: i18nRequired('form.dataDicItem','数据字典项必填')}] }]"
                                         @click="selectDic($event,'dicKey')"
                                         style="width: 100%;">
                        </rx-input-button>
                        <a-input v-decorator="['dicKey']" style="display: none;"/>
                    </a-form-item>

                    <div v-show="from=='sql'">
                        <a-form-item   :label="i18n('form.customSQL','自定义SQL')">
                            <rx-input-button ref="sql" @click="openCustomQuery" v-decorator="['sql',{rules: [{ required: from=='sql',message: i18nRequired('form.customSQL','自定义SQL必填')}] }]" />
                        </a-form-item>
                        <a-form-item  :label="i18n('form.textField','文本字段')">
                            <a-select :options="sqlFields" v-decorator="['sql_textfield',{rules: [{ required: from=='sql',message: i18nRequired('form.textField','文本字段必填')}] }]"/>
                        </a-form-item>

                        <a-form-item  :label="i18n('form.numberField','数值字段')">
                            <a-select :options="sqlFields" v-decorator="['sql_valuefield',{rules: [{ required: from=='sql',message: i18nRequired('form.numberField','数值字段必填')}] }]"/>
                        </a-form-item>
                    </div>
                </a-form>
            </div>
        </rx-layout>
    </rx-dialog>
</template>

<script>
    import {RxDialog, Util,RxGrid,Dialog,RxInputButton,RxLayout,App,JsConstant} from "@lowcode/jpaas-common-lib";
    import FormDbApi from "@/api/form/bo/formDb";
    import AppName from "@/assets/js/AppName.js";

    export default {
        name: "FormBoListSearchGroup",
        mixins:[App,AppName],
        components: {
            RxGrid,
            RxInputButton,
            RxLayout,
            RxDialog
        },
        props:["row","fieldDatas","layerid","destroy"],
        data(){
            return{
                labelCol: { span:6 },
                wrapperCol: { span:18 },
                labelCol1: { span:3 },
                wrapperCol1: { span:19 },
                form: this.$form.createForm(this),
                mdl:{},
                distinct_type:"",
                matchCol:[],
                from:"",
                fromOptions:[
                    {'value':'distinct','label':this.i18n('form.distinct','去重字段')},
                    {'value':'self','label':this.i18n('form.custom','自定义')},
                    {'value':'url','label':'URL'},
                    {'value':'dic','label':this.i18n('form.dict','数据字典')},
                    {'value':'sql','label':this.i18n('form.customSQL','自定义SQL')}
                ],
                dataSource:[],
                columns:[
                    {title: this.$ti18('rxList.index','序号'), type: 'indexColumn', width: 80, dataIndex: 'serial', scopedSlots: {customRender: 'serial'}},
                    {title: this.i18n('form.name','名称'), dataIndex: 'name', width: 120,allowCellEdit:true,scopedSlots: {customRender: 'name'}},
                    {title: this.i18n('form.markName','标识名'), dataIndex: 'key', width: 120,allowCellEdit:true,scopedSlots: {customRender: 'key'}}
                ],

                sqlFields:[]
            }
        },
        mounted(){
            this.setData(this.row);
        },
        methods:{
            i18n(name, text, key) {
                return this.$ti18(name, text, "formBoListDialog", key);
            },
            i18nRequired(name,text,key){
                let nameVal = this.$ti18(name,text,"formBoListDialog",key);
                let tipVal = this.i18n("form.required", "必填");
                return nameVal + tipVal;
            },
            //选择数据字典
            selectDic(vm,key){
              var conf = {
                curVm: this, data: {allowTree:false}, widthHeight: ['800px', '600px'],
              }
              let self_ = this;
              Dialog.openSysDicDialog(conf,function (curVue, row) {
                let json = {};
                json[key]=row.alias;
                json[key+'_name']=self_.$i18(row.name,"名称");
                self_.form.setFieldsValue(json);
                vm.setVal(json[key],json[key+'_name']);
              })
            },
            onOk(e){
                var self=this;
                this.form.validateFields((err, values) => {
                    if(err){
                        e.loading=false;
                        return;
                    }
                    self.mdl=values;
                    Util.closeWindow(self, "ok");
                })
            },
            cancel(){
                Util.closeWindow(this,"cancel");
            },
            fromChange(e){
                this.from=e.target.value;
                this.distinct_type='';
                this.form.setFieldsValue({distinct_type:''});
            },
            typeChange(e){
                this.distinct_type=e.target.value;
            },
            addRow(){
                this.$refs.props.addRow();
            },
            removeRow(){
                this.$refs.props.removeRows();
            },
            upRow(){
                this.$refs.props.moveUp();
            },
            downRow(){
                this.$refs.props.moveDown();
            },
            openFormEntityDataType(vm){
                var self=this;
                var config={curVm:this,widthHeight:['800px','600px'],data:{multiSelect:false}};
                Dialog.openFormEntityDataTypeDialog(config,function(ary){
                    var data=ary[0];
                    vm.setVal(data.id,data.name);
                })
            },
            openCustomQuery(vm){
                Dialog.openCustomDataDialog({
                    curVm: this, widthHeight: ['1200px', '600px']
                }, function (self, data) {
                    self.loadFields(data);
                    vm.setVal(data.key,data.name);
                })
            },
            loadFields(row){
                var fieldStr=row.resultField;
                if(fieldStr) {
                    var fileds = JSON.parse(fieldStr);
                    var ary = fileds.map(function (item) {
                        return {
                            value: item.fieldName,
                            label: item.comment
                        }
                    })
                    this.sqlFields = ary;
                }
            },
            openDataSource(vm) {
                Dialog.openDataSourceDialog({
                    curVm: this, widthHeight: ['1200px', '600px'],
                    data:{appName: this.serviceName}
                }, function (self, data) {
                    vm.setVal(data.alias, data.name)
                })
            },
            onTableMap(vm) {
                var datasource=this.form.getFieldValue("dsName");
                if(datasource){
                    datasource = JSON.parse(datasource).value;
                }
                else{
                    datasource = this.mdl.dsName;
                }
                Dialog.openTableQueryDialog({
                    curVm: this, widthHeight: ['1200px', '600px'], data: {ds: datasource}
                }, function (self, data) {
                    vm.setVal(data.tableName, data.tableName);
                    self.loadColumn(data.tableName);
                })
            },
            loadColumn(tableName){
                var self_  = this;
                var datasource = this.form.getFieldValue("dsName");
                if(datasource != undefined){
                    datasource = JSON.parse(datasource).value;
                }
                else{
                    datasource = "";
                }
                FormDbApi.getByName("dsName=" + datasource + "&tbName=" + tableName).then(data => {
                    var column = [];
                    for(var i = 0; i < data.columnList.length; i++){
                        column.push({label:data.columnList[i].comment,value:data.columnList[i].fieldName});
                    }
                    self_.matchCol = column;
                })
            },
            setData(data) {
                this.mdl=Object.assign({from:'distinct'},data);
                this.from=this.mdl.from;
                this.distinct_type=this.mdl.distinct_type;
                if(this.mdl.sql) {
                    this.mdl.sql = '{value:\'' + this.mdl.sql + '\',text:\'' + this.mdl.sql_name + '\'}';
                }
                this.sqlFields = this.mdl.sqlFields || [];
                var props=this.mdl.props || '[]';
                this.dataSource=JSON.parse(props);
                this.form.setFieldsValue(this.mdl);
                if(this.distinct_type=='table'){
                    let tableName=this.mdl.tableName;
                    if(tableName){
                        tableName=JSON.parse(tableName).value;
                        this.loadColumn(tableName);
                    }
                }
            },
            getData(){
                this.mdl.props = JSON.stringify(this.$refs.props.getData());
                var sql = this.$refs.sql.getVal();
                this.mdl.sql=sql.value;
                this.mdl.sql_name=sql.text;
                this.mdl.sqlFields=this.sqlFields;
                return this.mdl;
            }
        }
    }
</script>

<style scoped>

</style>